using System;
using System.Collections.Generic;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.Windows.Threading;
using Microsoft.Surface;
using Microsoft.Surface.Presentation;
using Microsoft.Surface.Presentation.Controls;
using System.Windows.Forms;
using System.Windows.Interop;

namespace LetsGoToSchool
{
    /// <summary>
    /// Interaction logic for ImageManager.xaml
    /// </summary>
    public partial class ImageManager : SurfaceWindow
    {
        private readonly int NUM_COLS = 3;
        private List<RowDefinition> _rows;
        private Dictionary<Contact, Point> _trackedContacts = new Dictionary<Contact, Point>();
        //private Form _window;

        /// <summary>
        /// A timer constantly checking the contacts, removes invalid contacts from _trackedContacts.
        /// It seems it's unnecessary for the moment, if in the future the contacts count goes wrong, 
        /// uncomment this.
        /// </summary>
        //private DispatcherTimer _contactTimer;

        /// <summary>
        /// Default constructor.
        /// </summary>
        public ImageManager()
        {
            InitializeComponent();

            // Add handlers for Application activation events
            AddActivationHandlers();

            _mockDialog.setManager(this);

            //load image from database
            _rows = new List<RowDefinition>();
            List<Image> images = Database.getAllImages();
            foreach (Image img in images)
            {
                this.addImage(img);
            }

            Contacts.AddContactDownHandler(this, HideAllFrames);
            Contacts.AddContactDownHandler(_allImages, HideAllFrames);

            // set up the contact checking timer
            /*_contactTimer = new DispatcherTimer();
            _contactTimer.Interval = TimeSpan.FromMilliseconds(100);
            _contactTimer.Tick += delegate(object sender, EventArgs e)
            {
                _contactTimer.Stop();
                try
                {
                    foreach (Contact c in _trackedContacts.Keys)
                    {
                        try
                        {
                            c.GetPosition(this);
                        }
                        catch (InvalidOperationException ex)
                        {
                            _trackedContacts.Remove(c);
                        }
                    }
                }
                finally
                {
                    _contactTimer.Start();
                }
            };*/

            /*_openFileDialog = new OpenFileDialog();

            _openFileDialog.Multiselect = true;
            _openFileDialog.CheckFileExists = true;
            _openFileDialog.Filter = "All images (*.jpg; *.png; *.bmp)|*.jpg;*.png;*.bmp|All Files (*.*)|*.*";

            _window = new Form();
            _window.StartPosition = FormStartPosition.Manual;
            _window.Location = new System.Drawing.Point(0, 0);*/
        }

        /// <summary>
        /// private helper to add a new row to the grid
        /// </summary>
        private void addRow()
        {
            RowDefinition row = new RowDefinition();
            row.Height = GridLength.Auto;
            _allImages.RowDefinitions.Add(row);
            _rows.Add(row);
        }

        /// <summary>
        /// adds an image to the next available position to the grid
        /// </summary>
        /// <param name="img"></param>
        public void addImage(Image img)
        {            
            int index = _allImages.Children.Count;
            if (index % NUM_COLS == 0)
            {
                this.addRow();
            }
            img.Width = 250;
            ImageFrame frame = new ImageFrame(img, this);
            _allImages.Children.Add(frame);
            Grid.SetRow(frame, _rows.Count - 1);
            Grid.SetColumn(frame, index % NUM_COLS);
        }

        public static String getIconFileName()
        {
            return "Icon-ImageManager.png";
        }

        /// <summary>
        /// release the used memory
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void _quitButton_Click(object sender, RoutedEventArgs e)
        {
            //_window.Dispose();
            //_openFileDialog.Dispose();
            _mockDialog.Close();
            Close();
        }

        /// <summary>
        /// brings up the openfiledialog
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void _uploadButton_Click(object sender, RoutedEventArgs e)
        {
            _mockDialog.Show();
            /*if (_openFileDialog.ShowDialog(_window) == System.Windows.Forms.DialogResult.OK)
            {

                string[] filePath = _openFileDialog.FileNames;
                string[] safeFilePath = _openFileDialog.SafeFileNames;

                //add to grid and put into database
                foreach (string path in filePath)
                {
                    Database.addImage(path.Replace("\\", "/"), "fruit");
                    this.addImage(Utils.loadImage(path));
                }

            }*/
        }

        private string[] _filePath;
        public void ShowTypeBox(string[] filePath)
        {
            _mockDialog.Visibility = Visibility.Hidden;
            NoContactGrid.Visibility = Visibility.Visible;
            _enterTypeBox.Visibility = Visibility.Visible;

            _filePath = filePath;
        }

        /// <summary>
        /// import image to the system
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void LoadImages(object sender, RoutedEventArgs e)
        {
            string type = "Default";
            if (!_typeText.Text.Equals(""))
            {
                type = _typeText.Text;
            }
            //add to grid and put into database
            foreach (string path in _filePath)
            {
                Database.addImage(path.Replace("\\", "/"), type);
                this.addImage(Utils.loadImage(path));
            }
            this.Hide_TypeBox();
        }

        private void CancelButton_Click(object sender, RoutedEventArgs e)
        {
            this.Hide_TypeBox();
        }

        private void Hide_TypeBox()
        {
            NoContactGrid.Visibility = Visibility.Hidden;
            _enterTypeBox.Visibility = Visibility.Hidden;
            _typeText.Text = "";
        }

        public void HideAllFrames(object sender, ContactEventArgs e)
        {
            foreach (ImageFrame image in _allImages.Children){
                image.hideFrame();
            }
        }

        public void HideAllBorders()
        {
            foreach (ImageFrame image in _allImages.Children)
            {
                image.hideBorder();
            }
        }

        /// <summary>
        /// keeps track of the number of contacts
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void SurfaceScrollViewer_PreviewContactDown(object sender, ContactEventArgs e)
        {
            _trackedContacts.Add(e.Contact, new Point(e.Contact.GetPosition(this).X, e.Contact.GetPosition(this).Y));
        }

        private void SurfaceScrollViewer_ContactLeave(object sender, ContactEventArgs e)
        {
            _trackedContacts.Remove(e.Contact);
        }

        public Dictionary<Contact, Point> getTrackedContacts()
        {
            return _trackedContacts;
        }

        /// <summary>
        /// Occurs when the window is about to close. 
        /// </summary>
        /// <param name="e"></param>
        protected override void OnClosed(EventArgs e)
        {
            base.OnClosed(e);

            // Remove handlers for Application activation events
            RemoveActivationHandlers();
        }

        /// <summary>
        /// Adds handlers for Application activation events.
        /// </summary>
        private void AddActivationHandlers()
        {
            // Subscribe to surface application activation events
            ApplicationLauncher.ApplicationActivated += OnApplicationActivated;
            ApplicationLauncher.ApplicationPreviewed += OnApplicationPreviewed;
            ApplicationLauncher.ApplicationDeactivated += OnApplicationDeactivated;
        }

        /// <summary>
        /// Removes handlers for Application activation events.
        /// </summary>
        private void RemoveActivationHandlers()
        {
            // Unsubscribe from surface application activation events
            ApplicationLauncher.ApplicationActivated -= OnApplicationActivated;
            ApplicationLauncher.ApplicationPreviewed -= OnApplicationPreviewed;
            ApplicationLauncher.ApplicationDeactivated -= OnApplicationDeactivated;
        }

        /// <summary>
        /// This is called when application has been activated.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void OnApplicationActivated(object sender, EventArgs e)
        {
            //TODO: enable audio, animations here
        }

        /// <summary>
        /// This is called when application is in preview mode.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void OnApplicationPreviewed(object sender, EventArgs e)
        {
            //TODO: Disable audio here if it is enabled

            //TODO: optionally enable animations here
        }

        /// <summary>
        ///  This is called when application has been deactivated.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void OnApplicationDeactivated(object sender, EventArgs e)
        {
            //TODO: disable audio, animations here
        }
    }
}